<?php
require_once ('config/path_config.php');
require_once ('config/sys_config.php');
require_once("include/db_info.inc.php");
require_once("include/const.inc.php");

// 判断用户是否已登录
if (!isset($_SESSION['user_id'])) {
    require_once("oj-header.php");
    echo "<a href='loginpage.php'>$MSG_Login</a>";
    require_once("oj-footer.php");
    exit(0);
}

$now=strftime("%Y-%m-%d %H:%M",time());
$user_id=$_SESSION['user_id'];
$user_name = $_SESSION['user_name'];

$sql="SELECT count(1) FROM `solution` WHERE result<4";
$result=pdo_query($sql);
$row=$result[0];

// 提交过于频繁,则要求用户输入验证码,延迟提交时间
if( $row[0] > 20 ) {
    $_SESSION["need_vcode"] = true;
}
else {
    $_SESSION["need_vcode"] = false;
}
$needVCode = SysConfig::$OJ_VCODE || $_SESSION["need_vcode"];

// 校验验证码
if ( $needVCode ) {
    // 暂未生成过验证码
    if ( !isset($_SESSION["vcode"]) || $_SESSION["vcode"] == null ) {
        echo "<script>alert('当前人数较多,请刷新后重新提交');window.history.go(-1);</script>";
        exit(0);
    }

    // 验证码输入错误
    $vcode = isset($_POST["vcode"]) ? $_POST["vcode"] : null;
    if ( $vcode != $_SESSION["vcode"] ) {
        echo "<script>alert('验证码错误,请输入正确的验证码,验证码区分大小写'); window.history.go(-1);</script>";
        exit(0);
    }
    $_SESSION["vcode"]=null;
}

$o2flag = 0;

if ( isset($_POST['o2flag']) ){
    $o2flag = 1;
}

if (isset($_POST['cid'])){
    $pid=intval($_POST['pid']);
    $cid=intval($_POST['cid']);
    $sql="SELECT `problem_id` from `contest_problem`
          where `num`='$pid' and contest_id=$cid";
}else{
	$id=intval($_POST['id']);
	$sql="SELECT `problem_id` from `problem` where `problem_id`='$id' and problem_id not in (select distinct problem_id from contest_problem where `contest_id` IN (
			SELECT `contest_id` FROM `contest` WHERE 
			(`end_time`>'$now' or private=1)and `defunct`='N'
			))";
	if(!isset($_SESSION['administrator']))
		$sql.=" and defunct='N'";
}

$res=pdo_query($sql);
if ($res&&count($res)<1&&!isset($_SESSION['administrator'])&&!((isset($cid)&&$cid<=0)||(isset($id)&&$id<=0))){
    $view_errors=  "Where do find this link? No such problem.<br>";
    require("template/".$OJ_TEMPLATE."/error.php");
    exit(0);
}

$test_run=false;
if (isset($_POST['id'])) {
	$id=intval($_POST['id']);
        $test_run=($id<=0);
}else if (isset($_POST['pid']) && isset($_POST['cid'])&&$_POST['cid']!=0){
	$pid=intval($_POST['pid']);
	$cid=intval($_POST['cid']);
        $test_run=($cid<0);
	if($test_run) $cid=-$cid;
	// check user if private
	$sql="SELECT `private` FROM `contest` WHERE `contest_id`=? AND `start_time`<=? AND `end_time`>?";
	$result=pdo_query($sql,$cid,$now,$now);
	$rows_cnt=count($result);
	if ($rows_cnt!=1){
		echo "You Can't Submit Now Because Your are not invited by the contest or the contest is not running!!";
		
		require_once("oj-footer.php");
		exit(0);
	}else{
		 $row=$result[0];
		$isprivate=intval($row[0]);
		
		if ($isprivate==1&&!isset($_SESSION['c'.$cid])){
			$sql="SELECT count(*) FROM `privilege` WHERE `user_id`=? AND `rightstr`=?";
			$result=pdo_query($sql,$user_id,"c$cid") ; 
			$row=$result[0];
			$ccnt=intval($row[0]);
			
			if ($ccnt==0&&!isset($_SESSION['administrator'])){
				$view_errors= "You are not invited!\n";
				require("template/".$OJ_TEMPLATE."/error.php");
				exit(0);
			}
		}
	}
	$sql="SELECT `problem_id` FROM `contest_problem` WHERE `contest_id`=? AND `num`=?";
	$result=pdo_query($sql,$cid,$pid);
	$rows_cnt=count($result);
	if ($rows_cnt!=1){
		$view_errors= "No Such Problem!\n";
		require("template/".$OJ_TEMPLATE."/error.php");
		
		exit(0);
	}else{
		 $row=$result[0];
		$id=intval($row['problem_id']);
		if($test_run) $id=-$id;
		
	}
}else{
       $id=0;
       $test_run=true;
}
$language=intval($_POST['language']);
if ($language>count($language_name) || $language<0) {
    $language=0;
}
$language=strval($language);

$source=$_POST['source'];
// 限制提交内容：过滤恶意提交，避免提交无聊代码
$ret = preg_match("/.*\s{80,}/i", $source, $match);
$ret |= preg_match("/[a-z A-Z 0-9]{150,}/i", $source, $match);
// 过滤关键函数
$ret |= preg_match("/system/i", $source, $match);
$ret |= preg_match("/exec/i", $source, $match);
$ret |= preg_match("/execl/i", $source, $match);
if ( $ret ) {
    echo "<script>alert('请注意代码的提交格式,不要胡乱提交代码'); window.history.go(-1);</script>";
    exit(0);
}

$input_text="";
if(isset($_POST['input_text'])) {
    $input_text=$_POST['input_text'];
}

if(get_magic_quotes_gpc()){
	$source=stripslashes($source);
	$input_text=stripslashes($input_text);
}
if(isset($_POST['encoded_submit'])){
   $source=base64_decode($source);
}

$input_text=preg_replace ( "(\r\n)", "\n", $input_text );
$source=($source);
$input_text=($input_text);
$source_user=$source;
if($test_run) $id=-$id;

$prepend_file="$OJ_DATA/$id/prepend.".$language_ext[$language];
if(isset($OJ_APPENDCODE)&&$OJ_APPENDCODE&&file_exists($prepend_file)){
     $source=file_get_contents($prepend_file)."\n".$source;
}
$append_file="$OJ_DATA/$id/append.".$language_ext[$language];
//echo $append_file;
if(isset($OJ_APPENDCODE)&&$OJ_APPENDCODE&&file_exists($append_file)){
     $source.=("\n".file_get_contents($append_file));
     //echo "$source";
}
//end of append 
if($language==6)
   $source="# coding=utf-8\n".$source;
if($test_run) {
    $id=0;
}

// 设置最后一次选择的语言
setcookie('lastlang',$language,time()+360000);

// 获取提交的ip
$ip = ($_SERVER['REMOTE_ADDR']);
if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ){
    $REMOTE_ADDR = $_SERVER['HTTP_X_FORWARDED_FOR'];
    $tmp_ip=explode(',',$REMOTE_ADDR);
    $ip =(htmlentities($tmp_ip[0],ENT_QUOTES,"UTF-8"));
}

// 判断代码长度
$len=strlen($source);
if ($len < 10) {
    $view_errors="Code too short!<br>";
    require("template/".$OJ_TEMPLATE."/error.php");
    exit(0);
}
if ($len > 65536 ) {
    $view_errors="Code too long!<br>";
    require("template/".$OJ_TEMPLATE."/error.php");
    exit(0);
}

// last submit
$now=strftime("%Y-%m-%d %X",time()-30);
$sql="SELECT `in_date` from `solution` where `user_id`=? and in_date>? order by `in_date` desc limit 1";
$res=pdo_query($sql,$user_id,$now);
// 普通用户每30秒内只允许提交1次
if (!isset($_SESSION['administrator']) && count($res)==1){
	
		$view_errors="提交操作过于频繁，每30秒内只允许提交一次.....<br>";
        $displayRet = true;
		require("template/".$OJ_TEMPLATE."/error.php");
		exit(0);
}
if((~$OJ_LANGMASK)&(1<<$language)){
    if (!isset($pid)){
        $sql="INSERT INTO solution(problem_id,user_id, user_name, `o2_flag`, in_date,language,ip,code_length,result)
                VALUES(?,?,?,?,NOW(),?,?,?,14)";
        $insert_id= pdo_query($sql, $id, $user_id, $user_name, $o2flag, $language, $ip, $len);
	}else{
        $sql="INSERT INTO solution(problem_id,user_id, user_name, `o2_flag`, in_date,language,ip,code_length,contest_id,num,result)
              VALUES(?,?,?,?,NOW(),?,?,?,?,?,14)";
        $insert_id= pdo_query($sql,$id, $user_id, $user_name, $o2flag, $language, $ip, $len, $cid, $pid);
    }

    $sql="INSERT INTO `source_code_user`(`solution_id`,`source`)VALUES(?,?)";
    pdo_query($sql,$insert_id,$source_user);
    $sql="INSERT INTO `source_code`(`solution_id`,`source`)VALUES(?,?)";
    pdo_query($sql,$insert_id,$source);
    /*
    if($test_run){
		$sql="INSERT INTO `custominput`(`solution_id`,`input_text`)VALUES(?,?)";
		pdo_query($sql,$insert_id,$input_text);
	}
    */
	$sql="update solution set result=0 where solution_id=?";
	pdo_query($sql,$insert_id);

	// 添加提交代码到redis数据库
    if($OJ_REDIS){
        $redis = new Redis();
        $redis->connect($OJ_REDISSERVER, $OJ_REDISPORT);
        if(isset($OJ_REDISAUTH)) $redis->auth($OJ_REDISAUTH);
            $redis->lpush($OJ_REDISQNAME,$insert_id);
            $redis->close();
        }
    }

    $statusURI=strstr($_SERVER['REQUEST_URI'],"submit",true)."status.php";
    if (isset($cid))
	    $statusURI.="?cid=$cid";
	    
        $sid="";
        if (isset($_SESSION['user_id'])){
                $sid.=session_id().$_SERVER['REMOTE_ADDR'];
        }
        if (isset($_SERVER["REQUEST_URI"])){
                $sid.=$statusURI;
        }
   // echo $statusURI."<br>";
  
        $sid=md5($sid);
        $file = "cache/cache_$sid.html";
    //echo $file;  
    if($OJ_MEMCACHE){
		$mem = new Memcache;
                if($OJ_SAE)
                        $mem=memcache_init();
                else{
                        $mem->connect($OJ_MEMSERVER,  $OJ_MEMPORT);
                }
        $mem->delete($file,0);
    }
	else if(file_exists($file)) 
	     unlink($file);
    //echo $file;
    
  $statusURI="status.php?user_id=".$_SESSION['user_id'];
  if (isset($cid)) {
      $statusURI.="&cid=$cid";
  }
   if(!$test_run){
      header ("Location: $statusURI");
   }
   else{
   	if( isset($_GET['ajax']) ) {
        echo $insert_id;
    }
    else{
?>
        <script>window.parent.setTimeout("fresh_result('<?php echo $insert_id;?>')",1000);</script>
<?php
        }
   }
?>
